package cn.satoken.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * <h3>saToken</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2025-06-06 10:34:17
 */
@RestController
@RequiredArgsConstructor
public class CommentController {
    private final DefaultKaptcha captchaProducer;
    @GetMapping("/api/captcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/png");

        // 生成验证码文本
        String capText = captchaProducer.createText();
        session.setAttribute("captcha", capText); // 存入 session

        // 生成验证码图片
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "png", out);

        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}
